package Hot100;

public class rotate_martix {
    public static void main(String[] args) {
        int[][] matrix= {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix.length; j++) {
                System.out.print(matrix[i][j] + "  ");
            }
            System.out.println();
        }
        System.out.println();
        rotate(matrix);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix.length; j++) {
                System.out.print(matrix[i][j] + "  ");
            }
            System.out.println();
        }
    }
    public static void rotate(int[][] matrix) {
        int count = 0;
        if(matrix.length % 2 ==0 )
             count = matrix.length / 2;
        else
             count = matrix.length / 2 + 1;

        if(count == 0)
            return;

        int m = matrix.length;
        int n = matrix[0].length;
        int circle = 1;

        int row = 0, col = 0;
        //先转动边,再转动每一圈的端点
        while(circle <= count){
            row = circle;
            col = circle - 1;
            for (int i = 0; i < matrix.length - 2 - 2 * (circle - 1); i++) {
                int temp = matrix[row][col];
                matrix[row][col] = matrix[m - circle][row];
                matrix[m - circle][row] = temp;
                row++;

            }
            row = m - circle;
            col = circle;
            for (int i = 0; i < matrix.length - 2 - 2 * (circle - 1); i++) {
                int temp = matrix[row][col];
                matrix[row][col] = matrix[m - col - 1][n - circle];
                matrix[m - col - 1][n - circle] = temp;
                col++;

            }
            row = circle;
            col = n - circle;
            for (int i = 0; i < matrix.length - 2 - 2 * (circle - 1); i++) {
                int temp = matrix[row][col];
                matrix[row][col] = matrix[circle - 1][row];
                matrix[circle - 1][row] = temp;
                row++;

            }
            int temp = matrix[circle - 1][circle - 1];
            matrix[circle - 1][circle - 1] = matrix[m - circle][circle - 1];
            matrix[m - circle][circle - 1] = matrix[m - circle][n - circle];
            matrix[m - circle][n - circle] = matrix[circle - 1][n - circle];
            matrix[circle - 1][n - circle] = temp;

            circle++;

        }
    }
}
